package com.atguigu.flink.day03;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.func.WaterSensorMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @author Felix
 * @date 2024/8/12
 * 该案例演示了聚合算子-sum
 * 需求：计算每个传感器采集的水位和
 * 注意：聚合算子只有经过keyby之后得到的键控流(分组流)才有
 */
public class Flink12_Transform_Sum {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //TODO 2.从指定的网络端口中读取数据
        DataStreamSource<String> ds = env.socketTextStream("hadoop102", 8888);
        //将流中数据进行类型转换 string->WaterSensor
        SingleOutputStreamOperator<WaterSensor> wsDS = ds.map(
                new WaterSensorMapFunction()
        );

        //TODO 3.按照传感器id进行分组
        KeyedStream<WaterSensor, String> keyedDS = wsDS.keyBy(WaterSensor::getId);
        //TODO 4.求和
        SingleOutputStreamOperator<WaterSensor> sumDS = keyedDS.sum("vc");
        //TODO 5.打印
        sumDS.print();
        //TODO 6.提交作业
        env.execute();
    }
}
